from ui.components.composite.form_layout import TgFormLayout
from ui.components.inputs.line_edit import TgLineEdit
from ui.components.buttons.button import TgButton
from ui.components.feedback.progress_bar import TgProgressBar
from ui.components.composite.table import TgTable
from ui.components.dialogs.file_dialog import TgFileDialog
from ui.components.dialogs.message_box import TgMessageBox
from typing import cast
from ..controllers.settings_controller import SettingsController


class SettingsTab(TgFormLayout):
    """设置 Tab - 视图层"""
    def __init__(self):
        super().__init__()
        
        # 初始化控制器
        self.controller = SettingsController()
        self._setup_ui()
        self._connect_signals()
        
        # 初始化数据
        self.controller.load_workspace()
        self.controller.load_contract_info()

    def _setup_ui(self):
        """设置UI组件"""
        # Workspace settings
        workspace_components = self.add_row_components(
            "工作区:",
            [
                {"component": "line_edit", "props": {}},
                {"component": "button", "props": {"text": "浏览", "size": "small", "callback": self.browse_workspace}},
            ]
        )
        self.workspace_line_edit = cast(TgLineEdit, workspace_components[0])
        self.browse_button = cast(TgButton, workspace_components[1])

        # Import historical data
        self.import_button = TgButton("导入", size="small")
        self.import_button.clicked.connect(self.import_historical_data)
        self.progress_bar = TgProgressBar()
        self.progress_bar.hide()
        self.add_row("导入历史数据:", self.import_button, self.progress_bar)

        # Import contract info
        self.import_contract_info_button = TgButton("导入合约信息", size="small")
        self.import_contract_info_button.clicked.connect(self.import_contract_info)
        self.add_row("导入合约信息:", self.import_contract_info_button)

        # Contract info table
        self.contract_info_table = TgTable(editable=False, font_size='small', highlight_on_selection=False)
        self.contract_info_table.setFixedHeight(200)
        self.add_row("合约信息:", self.contract_info_table)
    
    def _connect_signals(self):
        """连接控制器信号"""
        self.controller.workspace_loaded.connect(self.on_workspace_loaded)
        self.controller.contract_info_loaded.connect(self.on_contract_info_loaded)
        self.controller.import_progress_updated.connect(self.on_import_progress_updated)
        self.controller.operation_completed.connect(self.on_operation_completed)
        self.controller.operation_failed.connect(self.on_operation_failed)

    # UI 事件处理方法（仅处理UI交互，委托给控制器处理业务逻辑）
    def import_contract_info(self):
        """导入合约信息 - UI事件处理"""
        dialog = TgFileDialog(self)
        file_path = dialog.get_open_file_name(title="选择合约信息文件", extensions=["xlsx"])
        self.controller.import_contract_info(file_path)

    def import_historical_data(self):
        """导入历史数据 - UI事件处理"""
        dialog = TgFileDialog(self)
        file_path = dialog.get_open_file_name(title="选择历史数据文件", extensions=["parquet"])
        if file_path:
            self.progress_bar.setValue(0)
            self.progress_bar.show()
            self.import_button.setEnabled(False)
            
            def ui_callback():
                self.process_ui_events()
            
            self.controller.import_historical_data(
                self.workspace_line_edit.text(), 
                file_path, 
                ui_callback
            )

    def browse_workspace(self):
        """浏览工作区 - UI事件处理"""
        original_path = self.workspace_line_edit.text()
        dialog = TgFileDialog(self)
        directory = dialog.get_existing_directory(title="选择工作区")
        if directory:
            new_path = self.controller.browse_and_set_workspace(directory, original_path)
            self.workspace_line_edit.setText(new_path)
    
    # 控制器信号响应方法（更新UI状态）
    def on_workspace_loaded(self, workspace_path: str):
        """工作区加载完成"""
        self.workspace_line_edit.setText(workspace_path)
    
    def on_contract_info_loaded(self, headers: list, data: list):
        """合约信息加载完成"""
        self.contract_info_table.set_data(headers, data)
    
    def on_import_progress_updated(self, progress: int):
        """导入进度更新"""
        self.progress_bar.setValue(progress)
    
    def on_operation_completed(self, title: str, message: str):
        """操作成功完成"""
        if "历史数据" in message:
            self.progress_bar.hide()
            self.import_button.setEnabled(True)
        TgMessageBox.information(self, title, message)
    
    def on_operation_failed(self, title: str, message: str):
        """操作失败"""
        if "导入历史数据" in message:
            self.progress_bar.hide()
            self.import_button.setEnabled(True)
        TgMessageBox.warning(self, title, message)